package com.zhuchaooasystem.ui.home.service;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.adapter.holder.NewUnusualHolder;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.presenter.home.servicenewunusual.ServiceNewUnusualContract;
import com.zhuchaooasystem.presenter.home.servicenewunusual.ServiceNewUnusualPresenter;
import com.zhuchaooasystem.ui.common.ImagePagerActivity;
import com.zhuchaooasystem.ui.common.LocalAlbumActivity;
import com.zhuchaooasystem.utils.AppUtils;
import com.zhuchaooasystem.utils.CameraUtils;
import com.zhuchaooasystem.utils.ListUtils;
import com.zhuchaooasystem.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ServiceNewUnusualActivity extends BaseActivity<ServiceNewUnusualPresenter> implements ServiceNewUnusualContract.View {
    private final int UPLOAD_IMAGE_MAX = 9;

    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    @BindView(R.id.actionbar_txt_right)
    TextView txt_right;
    //----
    @BindView(R.id.act_new_service_unusual_edit_content)
    EditText edit_content;
    @BindView(R.id.act_new_service_unusual_recycle)
    EasyRecyclerView recycle;

    private CameraUtils util_camera;
    //----
    private final int numColomn = 3; //每一行图片的数量
    private boolean delete;
    private List<String> imageList;
    private RecyclerArrayAdapter adapter;
    //----
    private InputMethodManager imm;
    //----
    private int projectId;
    private String orderCode;

    @Override
    protected int getLayout() {
        return R.layout.activity_new_service_unusual;
    }

    @Override
    protected ServiceNewUnusualPresenter getPresenter() {
        return new ServiceNewUnusualPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        if (null != getIntent() && null != getIntent().getExtras()) {
            projectId = getIntent().getExtras().getInt("projectId");
            orderCode = getIntent().getExtras().getString("orderCode");
        }
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        delete = false;
        imageList = new ArrayList<>();
        imageList.add(String.valueOf(R.drawable.ic_add_image)); //添加图片
        RxBus.get().register(this);
        util_camera = new CameraUtils();
    }


    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("localAlbum")})
    public void localAlbum(BaseEvent baseEvent) {
        if (null != baseEvent && null != baseEvent.event) {
            List<String> images = (List<String>) baseEvent.event;
            imageList = ListUtils.listPlus(images, imageList);
            adapter.clear();
            adapter.addAll(imageList);
        }
    }


    @Override
    protected void initView() {
        setActionBar();
        //----
        initRecycle();
    }

    private void initRecycle() {
        recycle.setLayoutManager(new GridLayoutManager(mContext, numColomn));
        recycle.setAdapterWithProgress(adapter = new RecyclerArrayAdapter<String>(mContext, imageList) {

            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new NewUnusualHolder(parent, ServiceNewUnusualActivity.this);
            }
        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //最后一张实现添加图片功能
                if (position == imageList.size() - 1) {
                    mPresenter.showPickDialog();
                } //正常图片点击进入大图查看
                else {
                    ArrayList<String> list_images_temp = new ArrayList<>();
                    list_images_temp.addAll(imageList);
                    list_images_temp.remove(imageList.size() - 1);
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("images", list_images_temp);
                    bundle.putInt("position", position);
                    bundle.putBoolean("isCache", false);
                    AppUtils.jump(mContext, ImagePagerActivity.class, bundle);
                }
            }
        });
        adapter.setOnItemLongClickListener(new RecyclerArrayAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(int position) {
                //长按出现删除按钮
                delete = true;
                adapter.notifyDataSetChanged();
                return false;
            }
        });
    }

    private void setActionBar() {
        txt_title.setText(getString(R.string.actionbar_title_new_service_unusual));
        txt_right.setText("提交");
        iv_back.setVisibility(View.VISIBLE);
        txt_right.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initDataAndLoadData() {
    }

    @OnClick({R.id.actionbar_iv_back, R.id.actionbar_txt_right})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                finish();
                break;
            //提交
            case R.id.actionbar_txt_right:
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
                mPresenter.submit();
                break;
        }
    }


    @Override
    public void onItemDeleteClick(int position) {
        //删除图片
        if (position != imageList.size() - 1) {
            if (null != imageList) {
                imageList.remove(position);
            }
            adapter.clear();
            adapter.addAll(imageList);
        }
    }

    @Override
    public void onCameraClick() {
        if ((imageList.size() - 1) >= UPLOAD_IMAGE_MAX) {
            ToastUtil.showShort(mContext, "最多上传" + UPLOAD_IMAGE_MAX + "张图片");
        } else {
            //拍照权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                requestPermission(new String[]{Manifest.permission.CAMERA}, Key.CAMERA);
            } else {
                //----拍照
                util_camera.takePhoto(mContext);
            }
        }
    }

    @Override
    public void onAlbumClick() {
        //----本地上传
        if ((imageList.size() - 1) >= UPLOAD_IMAGE_MAX) {
            ToastUtil.showShort(mContext, "最多上传" + UPLOAD_IMAGE_MAX + "张图片");
        } else {
            Bundle bundle = new Bundle();
            bundle.putInt("image_max", UPLOAD_IMAGE_MAX);
            bundle.putInt("image_cur", imageList.size() - 1);
            AppUtils.jump(mContext, LocalAlbumActivity.class, bundle);
        }
    }

    @Override
    public String getContent() {
        return edit_content.getText().toString();
    }

    @Override
    public int getProjectId() {
        return projectId;
    }

    @Override
    public String getOrderCode() {
        return orderCode;
    }

    @Override
    public List<String> getImageList() {
        return imageList;
    }

    @Override
    public void setClickable(boolean clickable) {
        txt_right.setClickable(clickable);
    }

    @Override
    public void submitSuccuss() {
        ToastUtil.showShort(mContext, "提交成功");
        RxBus.get().post("newUnusual", new BaseEvent<>());
        finish();
    }

    public boolean isDelete() {
        return delete;
    }

    public void setDelete(boolean delete) {
        this.delete = delete;
    }

    public int getNumColomn() {
        return numColomn;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }

    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case Key.CAMERA:
                //----拍照
                util_camera.takePhoto(mContext);
                break;
        }
    }

    /**
     * 权限失败回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_UP) {
            if (delete) {
                delete = false;
                adapter.notifyDataSetChanged();
                return true;
            } else {
                return super.dispatchKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            String path = CameraUtils.imagePath;
            CameraUtils.imagePath = "";
            imageList.add(0, path);
            adapter.clear();
            adapter.addAll(imageList);
        }
    }
}
